package integral

import (
	"context"
	"fmt"
	"strings"

	"mall/common/modelx"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/user/model"
	"mall/service/user/rpc/internal/svc"
	"mall/service/user/rpc/types/user"

	"github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetIntegralTaskLogListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetIntegralTaskLogListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetIntegralTaskLogListLogic {
	return &GetIntegralTaskLogListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetIntegralTaskLogListLogic) GetIntegralTaskLogList(in *user.BaseListReq) (*user.IntegralTaskLogListResp, error) {
	logx.Infof("GetIntegralTaskLogList : %+v ", in)

	if in.Filter == nil || len(*in.Filter) == 0 {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	// preloadMap, eagerLoadMap := modelx.ParsePreloadAndEagerLoad(in.Preload, in.EagerLoad)
	preloadMap, _ := modelx.ParsePreloadAndEagerLoad(in.Preload, in.EagerLoad)
	// logrus.Info(fmt.Sprintf("GetIntegralTaskLogList preloadMap: %+v", preloadMap))
	// map[userTransactionLog:[Id UserId UserName AssetType ChangeType ChangeAmount OldAmount SourceType SourceId Desc Status CreatedAt UpdatedAt]]

	// logrus.Info(fmt.Sprintf("GetIntegralTaskLogList eagerLoadMap: %+v", eagerLoadMap))
	// map[]

	userIntegralTaskEntityName := model.RpcEntityNames.UserTaskLog
	if _, ok := model.RpcEntityPreloadMap[userIntegralTaskEntityName]; !ok {
		return &user.IntegralTaskLogListResp{}, nil
	}

	userIntegralTaskRepositoryName := model.RepositoryNames.UserTaskLog
	columnMap, ok := model.RepositoryPreloadMap[userIntegralTaskRepositoryName]
	if !ok {
		return &user.IntegralTaskLogListResp{}, nil
	}

	var selectCols []string
	if preloadFields, hasPreloadFields := preloadMap[userIntegralTaskEntityName]; hasPreloadFields {
		selectCols = modelx.ParseSelectColumns(preloadFields, columnMap)
	}

	filterMap := modelx.ParseFilter(in.Filter, columnMap)
	// logrus.Info(fmt.Sprintf("GetIntegralTaskLogList filterMap: %+v", filterMap))
	// map[user_id:map[equalTo:[10021]]]
	if filterMap == nil {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	orderBy := modelx.ParseSorter(in.Sorter, columnMap)
	logrus.Info(fmt.Sprintf("GetIntegralTaskLogList orderBy: %s", orderBy))
	if len(orderBy) == 0 {
		orderBy = model.UserTaskLogColumns.ID + " DESC"
	}

	res, count, err := l.svcCtx.CurrentUser.GetTaskLogList(l.ctx, model.M{
		"offset": in.Offset,
		"limit":  in.Limit,
		// "search":  in.Search,
		"orderBy": orderBy,
		"select":  strings.Join(selectCols, ","),
	}, 2, filterMap)
	if err != nil {
		return nil, err
	}

	hasNextPage, hasPreviousPage := modelx.ParseCount(count)
	resp := &user.IntegralTaskLogListResp{
		HasNextPage:     &hasNextPage,
		HasPreviousPage: &hasPreviousPage,
	}

	if len(res) > 0 {
		for _, v := range res {
			resp.List = append(resp.List, &user.IntegralTaskLogInfo{
				Id:        &v.ID,
				UserId:    &v.UserID,
				TaskId:    &v.TaskID,
				TaskName:  &v.TaskName,
				TaskSlug:  &v.TaskSlug,
				Gems:      pointy.GetPointer(uint64(v.Gems)),
				Growth:    pointy.GetPointer(uint64(v.Growth)),
				Integrals: pointy.GetPointer(uint64(v.Integrals)),
				Status:    pointy.GetPointer(uint32(v.Status)),
				CreatedAt: pointy.GetPointer(modelx.FormatTime(v.CreatedAt, "")),
				UpdatedAt: pointy.GetPointer(modelx.FormatTime(v.UpdatedAt, "")),
			})
		}
	}
	resp.Total = uint64(len(resp.List))

	return resp, nil
}
